package cn.bitkit.assist.database;

import cn.bitkit.tools.file.FileUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class ScriptHelper {

    public static void execute(String file) {
        System.out.println(file);
        Path path = Path.of(file);
        if(Files.isDirectory(path)){
            File[] files = path.toFile().listFiles();
            for(File subFile : files){
                execute(subFile.getAbsolutePath());
            }
            return;
        }
        List<String> list = loadScript(file);
        for(String sql : list){
            System.out.println("---------------");
            System.out.println(sql);
        }
    }

    public static List<String> loadScript(String file){
        List<String> lineList = FileUtil.readAllLines(file);
        return mergeLine(lineList);
    }

    public static List<String> mergeLine(List<String> lineList){
        List<String> list = new ArrayList<>();
        boolean end = true;
        for(String e : lineList){
            if(end){
                list.add(e);
            }else{
                String s = list.remove(list.size()-1);
                list.add(s+"\n"+e);
            }
            if(e.trim().endsWith(";")){
                end = true;
            }else{
                end = false;
            }
        }
        return list;
    }

}
